package com.train.forum.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.forum.mapper.UserMapper;
import com.train.forum.pojo.po.User;
import com.train.forum.pojo.vo.UserViewVo;
import com.train.forum.service.UserService;
import com.train.forum.utils.R;
import com.train.forum.utils.Rs;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @Desc: 用户业务层，做业务逻辑
 * @Author: wjl
 * @DateTime: 2025/05/12 20:19:15
 */
@Service
@RequiredArgsConstructor

public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    private final UserMapper mapper;
    /**
     * @param phone 手机号
     * @param password 密码
     * @Desc: 用户登录
     * @Author: wjl
     * @DateTime: 2025/05/12 20:17:51
     * @Return: @return {@link String }
     */
    @Override
    public R login(@RequestBody String phone, String password) {
        User user=mapper.selectByPhone(phone);
        if(user==null){
            return Rs.error();
        }
        if (user.getPassword().equals(password)) {
            //登录成功时保存用户id到内存中
            StpUtil.login(user.getId());
            //获取token对象
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

            UserViewVo userViewVo = new UserViewVo();
            userViewVo.setPhone(user.getPhone());
            userViewVo.setTokenName( tokenInfo.getTokenName());
            userViewVo.setTokenValue( tokenInfo.getTokenValue());
            return Rs.success(userViewVo);
        }
        return Rs.error();
    }
    /**
     * @param id
     * @Desc: 通过用户id获取用户记录
     * @Author: wjl
     * @DateTime: 2025/05/13 15:16:56
     * @Return: @return {@link User }
     */
    @Override
    public User getById(Integer id) {
        return mapper.selectById(id);
    }
    public String  add(User user) {
        int insert = mapper.insert(user);
        if (insert > 0) {
            return "200";
        }else {
            return "500";
        }
    }

    public void update(User user) {
        int i = mapper.updateById(user);
        if (i>0){
            //修改成功
        }else {
            //修改失败
        }
    }

    public void delete(Integer id) {
        int i = mapper.deleteById(id);
        if (i>0){
            //修改成功
        }else {
            //修改失败
        }
    }


}
